package com.alibaba.middleware.hsf.guide.server.db;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.xml.FlatXmlDataSetBuilder;
import org.dbunit.operation.DatabaseOperation;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

/**
 * @author weipeng2k 2015年9月23日 下午4:26:44
 */
public class TableCreator extends JdbcDaoSupport {
    
    static final String CREATE_ORDER = readFileAsString("/db/order_main.sql");
    
    public void initial() {
        getJdbcTemplate().execute(CREATE_ORDER);
        try {
            IDatabaseConnection connection = new DatabaseConnection(getJdbcTemplate().getDataSource().getConnection());
            FlatXmlDataSetBuilder builder = new FlatXmlDataSetBuilder();
            DatabaseOperation.CLEAN_INSERT.execute(connection,
                                                   builder.build(TableCreator.class.getResourceAsStream("/db/order_main.xml")));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    private static final String readFileAsString(String path) {
        BufferedReader br = new BufferedReader(new InputStreamReader(TableCreator.class.getResourceAsStream(path)));
        String line = null;
        StringBuilder sb = new StringBuilder();
        try {
            while((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        return sb.toString();
    }
    
}
